/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>

*/
package cmd

import (
	"os"

	"gitee.com/bjf-fhe/apicat/platform"
	"gitee.com/bjf-fhe/apicat/report"
	"gitee.com/bjf-fhe/apicat/result"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

// reportCmd represents the report command
var reportCmd = &cobra.Command{
	Use:   "report",
	Short: "生成访问日志报告",
	Long:  `读取Nginx或者阿里云导出的csv访问日志，分析访问行为，生成访问报告`,
	Run: func(cmd *cobra.Command, args []string) {

		logrus.Infoln("开始执行Apicat报告生成程序")

		api, baseUrl, err := rootConfig.LoadApi(true)
		if err == nil {
			if len(args) > 0 {
				rootConfig.File = args[0]
			} else if !rootConfig.RemoteAggregationAsMain {
				logrus.Errorln("没有指定日志文件路径或在远程模式下运行")
				os.Exit(1)
			}

			var stat result.StatReader

			var f *os.File
			var dest = "report.html"
			f, err = os.OpenFile(dest, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
			if err == nil {
				logrus.Info("打开目标报告文件成功")
				defer f.Close()
				stat, err = report.Do(&rootConfig, api, baseUrl, f, runningCtx)
			} else {
				logrus.WithError(err).Errorln("打开目标报告文件失败")
			}
			if err == nil {
				cmd.Println("分析完毕！")
				cmd.Printf("总共%d条日志信息，详情如下：\n%s", stat.GetTotal(),
					stat.GetDetail())
				result.OpenResult()
			} else {
				logrus.Fatal(err)
			}
		} else {
			cmd.PrintErrln(err)
			os.Exit(1)
		}
	},
}

func init() {
	rootCmd.AddCommand(reportCmd)

	// Here you will define your flags and configuration settings.

	platform.AddFlags(reportCmd.PersistentFlags())
	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// reportCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// reportCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
